<template>
 <div class="container-card" ref="list">
   <xdh-scroll :on-reach-bottom="handleReachBottom" 
   :distance-to-edge="-100" :height="listHeight"
   :loading-text="'正在加载...'">
   <el-row>
     <el-col :span="12" v-for="(item, idx) in list" :key="idx">
       <card-item :item="item" :index="idx"></card-item>
     </el-col>
   </el-row>
   </xdh-scroll>
 </div>
</template>
<script>
import cardItem from './card-item'
import XdhScroll from '@/widgets/xdh-scroll/xdh-scroll'
import {mapState} from 'vuex'
import mSearch from '@/base/mixin/m-search'
export default {
    mixins: [mSearch],
    components: {
      cardItem,
      XdhScroll
    },
    data () {
      return {
        listHeight: 500,
        list: []
      }
    },
    computed: {
      ...mapState(['mySearchResult_mode', 'mySearchResult_query'])
    },
    watch: {
      mySearchResult_mode: {
        handler(val) {
          if(val === 'card') {
             this.fetchList();
            this.$nextTick(() => {
              this.handleResize();
            })
          }
        },
        immediate: true
      },
       mySearchResult_query: {
        deep: true,
        immediate: true,
        handler(val) {
          if(this.mySearchResult_mode === 'card') {
            this.fetchList();
          }
        }
      }
    },
    methods: {
      handleResize() {
        const rect = this.$refs.list.getBoundingClientRect()
        this.listHeight = rect.height;
      },
      handleReachBottom() {
        return new Promise(resolve => {
                    this.getSearchResultList(this.mySearchResult_query).then(res => {
          console.log(res)
          let key = this.mySearchResult_query.key;
           res.list.forEach(item => {
             for(let i in item) {
               item[i] = item[i].replace(new RegExp(key, 'gi'), function(subval) {
                     return '<mark>' + subval + '</mark>';
                      })
             }
             this.list.push(item)
           })
           resolve();
        })
                });
      },
      fetchList() {
        this.getSearchResultList(this.mySearchResult_query).then(res => {
          console.log(res)
          let key = this.mySearchResult_query.key;
           res.list.forEach(item => {
             for(let i in item) {
               item[i] = item[i].replace(new RegExp(key, 'gi'), function(subval) {
                     return '<mark>' + subval + '</mark>';
                      })
             }
             this.list = res.list;
           })
        })
        // val = val.replace(new RegExp(key.replace(/^\||\|$/, ''), 'gi'), function(subval) {
        //   return '<mark>' + subval + '</mark>';
        // });
        // return val
      }
    },
    mounted() {
      this.$nextTick(() => {
        this.handleResize();
      })
      window.addEventListener('resize', this.handleResize.bind(this))
    },
    created() {
    }
  }
</script>